package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.ApiDingDan;
import cn.com.api.entity.ApiT_city;
import cn.com.api.entity.ApiT_member;
import cn.com.api.entity.ApiT_order;
import cn.com.api.entity.ApiT_order_detail;
import cn.com.api.entity.ApiT_user_cash_records;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.ApiU_advert;
import cn.com.api.entity.ApiU_bonus;
import cn.com.api.entity.ApiU_coupon;
import cn.com.api.entity.ApiU_coupon_detail;
import cn.com.api.entity.ApiU_message;
import cn.com.api.mapper.ApiCarMapper;
import cn.com.api.mapper.ApiDingDanMapper;
import cn.com.api.mapper.ApiT_cityMapper;
import cn.com.api.mapper.ApiT_memberMapper;
import cn.com.api.mapper.ApiT_orderMapper;
import cn.com.api.mapper.ApiT_order_detailMapper;
import cn.com.api.mapper.ApiT_productsMapper;
import cn.com.api.mapper.ApiT_user_cash_recordsMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.mapper.ApiU_advertMapper;
import cn.com.api.mapper.ApiU_bonusMapper;
import cn.com.api.mapper.ApiU_couponMapper;
import cn.com.api.mapper.ApiU_coupon_detailMapper;
import cn.com.api.mapper.ApiU_messageMapper;
import cn.com.api.requestpage.PaytypeConfirmPage;
import cn.com.api.resultpage.CarOrderPage;
import cn.com.api.resultpage.InitPaymentPage;
import cn.com.api.service.ApiPaymentService;
import cn.com.api.service.ApiTOrderMessageService;
import cn.com.api.service.ApiT_orderService;
import cn.com.api.service.ApiT_shippingService;
import cn.com.pingpp.PingppUtil;
import cn.com.util.*;

@Service
public class ApiPaymentServiceImpl implements ApiPaymentService {

	@Autowired
	private ApiT_shippingService apiT_shippingService;
	@Autowired
	private ApiTOrderMessageService apiTOrderMessageService;
	@Autowired
	private ApiU_advertMapper advertMapper;
	@Autowired
	private ApiU_bonusMapper apiU_bonusMapper;
	@Autowired
	private ApiDingDanMapper apiDingDanMapper;
	@Autowired
	private ApiT_cityMapper cityMapper;
	@Autowired
	private ApiT_memberMapper apiT_memberMapper;
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;
	@Autowired
	private ApiT_orderService apiT_orderService;
	@Autowired
	private ApiT_user_cash_recordsMapper apiT_user_cash_recordsMapper;
	@Autowired
	private ApiT_order_detailMapper apiT_order_detailMapper;
	@Autowired
	private ApiT_orderMapper apiT_orderMapper;
	@Autowired
	private ApiT_productsMapper apiT_productsMapper;
	@Autowired
	private ApiCarMapper apiCarMapper;
	@Autowired
	private ApiU_coupon_detailMapper apiU_coupon_detailMapper;
	@Autowired
	private ApiU_couponMapper apiU_coupon_Mapper;
	@Autowired
	private ApiU_messageMapper apiU_messageMapper;

	private static Logger logger = Logger.getLogger(ApiPaymentServiceImpl.class);

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void payStatusWriteBack(Map<String, String> params, Map<String, Object> map) throws Exception {
		String order_no = params.get("serialflagno");
		String serial = params.get("serial");
		String channel = params.get("channel");
		String amount = params.get("amount");
		// 金额
		BigDecimal money = new BigDecimal(amount).divide(new BigDecimal("100"));
		List<ApiT_order> list = apiT_orderService.findOrderByMap(params);
		String nowTimeToString = DateUtil.nowTimeToString();
		if (!Util.isNull(list) && list.size() > 0) {
			ApiU_message message = new ApiU_message();
			// 资金变动的用户
			String user_id = list.get(0).getUser_id();
			// 用户金额变动明细表中插信息
			ApiT_user_cash_records apiT_user_cash_records = new ApiT_user_cash_records();
			apiT_user_cash_records.setUser_id(user_id);
			for (ApiT_order apiT_order : list) {
				apiT_order.setZi_status(1);// 已支付
				apiT_order.setDd_status(2);// 已付款
				apiT_order.setZf_type(PingppUtil.FormatPayType(channel));
				apiT_order.setSerial(serial);// 支付平台交易号
				apiT_order.setPaytime(nowTimeToString);
				apiT_orderService.updateT_order(apiT_order);
				apiT_user_cash_records.setCate_type(apiT_order.getOrdertype());
				map.put("did", apiT_order.getOrdernum());
				ApiT_order_detail apiT_order_detail = apiT_order_detailMapper.findOrderDetailsByMap(map);

				// 广告订单
				if (apiT_order.getOrdertype() == 5) {
					// 广告改为已支付状态
					ApiU_advert advert = advertMapper
							.findU_advertById(Integer.valueOf(apiT_order_detail.getTarget_id()));
					advert.setIs_pay(1);
					advertMapper.updateU_advert(advert);
					// 如果有红包，更新红包的支付状态
					if (advert.getBonus_id() != null && !"".equals(advert.getBonus_id())) {
						ApiU_bonus apiU_bonus = apiU_bonusMapper.findU_bonusById(Integer.valueOf(advert.getBonus_id()));
						apiU_bonus.setIs_pay(1);
						apiU_bonusMapper.updateU_bonus(apiU_bonus);
					}
					apiT_user_cash_records.setRemark("购买广告");
					message.setTitle("广告购买");
					message.setContent("广告购买成功");
				} else if (apiT_order.getOrdertype() == 6) {
					// 普通红包改为已支付状态
					ApiU_bonus apiU_bonus = apiU_bonusMapper
							.findU_bonusById(Integer.valueOf(apiT_order_detail.getTarget_id()));
					apiU_bonus.setIs_pay(1);
					apiU_bonusMapper.updateU_bonus(apiU_bonus);
					apiT_user_cash_records.setRemark("发红包");
				} else if (apiT_order.getOrdertype() == 0) { // 购物订单
					apiT_orderMapper.updateDDStatusBySerialFlagNo(order_no, "2");// 已付款
					// 扣减库存
					List<ApiT_order_detail> orderDetailList = apiT_order_detailMapper
							.getOrderDetailBySerialFlagNo(order_no);
					for (ApiT_order_detail orderDetailObj : orderDetailList) {
						String store = apiT_productsMapper.searStoreByProId(orderDetailObj.getProduct_id().toString());
						long num = orderDetailObj.getNum();
						int left = (int) (Integer.parseInt(store) - num);
						apiT_productsMapper.updStoreByProId(orderDetailObj.getProduct_id(), left);
					}
					// 修改购物车
					List<String> cardIdList = apiT_orderMapper.getCardIdsBySerialFlagNo(order_no);
					for (int i = 0; i < cardIdList.size(); i++) {
						apiCarMapper.updateCarByCarId(cardIdList.get(i), "1");// 已支付
					}
					apiT_user_cash_records.setRemark("购买了商品");
					message.setTitle("您的宝贝购买成功");
					message.setContent("您在首媒中国-特卖会的订单付款成功，宝贝已整装待发，请耐心等待哦");
				} else if (apiT_order.getOrdertype() == 1) {// 充值订单
					ApiT_member apiT_member = apiT_memberMapper
							.findT_memberById(Integer.valueOf(apiT_order.getUser_id()));
					apiT_member.setC_money(apiT_member.getC_money().add(money));
					apiT_memberMapper.updateT_member(apiT_member);
					apiT_user_cash_records.setRemark("充值");
					message.setTitle("您的充值订单已付款");
					message.setContent("您的充值订单付款成功");
				} else if (apiT_order.getOrdertype() == 11) {// 转账
					String touserId = apiT_order.getExt_1();// 转给某用户的
					ApiT_member toMember = apiT_memberMapper.findT_memberById(Integer.valueOf(touserId));
					String createType = apiT_order.getExt_2();// 是否需要对方接受转账
					if ("0".equals(createType)) { // 0-扫码支付（转账），不需要对方确认
						apiT_user_cash_records.setIs_receive(1);// 已领取

						// 已领取则增加一条已领取的记录
						ApiT_user_cash_records receiverecords = new ApiT_user_cash_records();
						receiverecords.setUser_id(touserId);
						receiverecords.setConn_id(apiT_order.getUser_id());
						receiverecords.setCate_type(7);
						receiverecords.setRemark(apiT_order.getC_nick() + " 转账给我");
						receiverecords.setProcess_type(0);
						receiverecords.setIs_receive(1);
						receiverecords.setCreate_time(nowTimeToString);
						receiverecords.setMoney(money);
						receiverecords.setOrder_id(order_no);
						receiverecords.setPay_type(0);
						receiverecords.setPay_type_desc("0");
						apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(receiverecords);

						toMember.setC_money(toMember.getC_money().add(money));
						apiT_memberMapper.updateT_member(toMember);
						//
						ApiU_message receivemessage = new ApiU_message();
						receivemessage.setContent(apiT_order.getC_nick() + "给您转账了" + money + "元");
						receivemessage.setTitle("转账");
						receivemessage.setType(10);
						receivemessage.setAdd_time(nowTimeToString);
						receivemessage.setConn_id(list.get(0).getRid());
						receivemessage.setUser_id(toMember.getC_id() + "");
						receivemessage.setIs_read(0);
						apiU_messageMapper.insertU_message(receivemessage);
					} else if ("1".equals(createType)) {// 1-表示普通的转账，需要对方确认，
						apiT_user_cash_records.setIs_receive(0);// 未领取
					}
					apiT_user_cash_records.setRemark("转账给 " + toMember.getC_nick());
					apiT_user_cash_records.setConn_id(touserId);
					apiT_user_cash_records.setCate_type(7);
				}
			}

			if (list.get(0).getOrdertype() == 1) {// 充值订单
				apiT_user_cash_records.setProcess_type(0);
				message.setContent("充值了" + money + "元");
				message.setTitle("充值成功");
				message.setType(7);
			} else if (list.get(0).getOrdertype() == 11) {// 转账
				message.setContent(" 转出了" + money + "元");
				message.setTitle("转账成功");
				message.setType(10);
			} else {// 非充值订单
				apiT_user_cash_records.setProcess_type(1);
				message.setType(7);
			}

			apiT_user_cash_records.setCreate_time(nowTimeToString);
			apiT_user_cash_records.setMoney(money);
			apiT_user_cash_records.setOrder_id(order_no);
			apiT_user_cash_records.setPay_type(1);
			apiT_user_cash_records.setPay_type_desc(PingppUtil.FormatPayType(channel));
			// 根据是否是充值订单判断是收入还是支出
			apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(apiT_user_cash_records);

			message.setAdd_time(nowTimeToString);
			message.setConn_id(list.get(0).getRid());
			message.setUser_id(user_id);
			message.setIs_read(0);
			apiU_messageMapper.U_messageInsertion(message);
		}
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void balancePayment(Map<String, Object> params, Map<String, Object> map) throws Exception {
		// 根据订单号查询订单信息
		String user_id = params.get("user_id").toString();
		String password = params.get("password").toString();
		String serialflagno = params.get("serialflagno").toString();
		BigDecimal amount = new BigDecimal(params.get("amount").toString());
		ApiT_member apiT_member = apiT_memberMapper.findT_memberById(Integer.valueOf(user_id));

		if (apiT_member.getPay_pwd() != null && !"".equals(apiT_member.getPay_pwd())) {
			if (!CipherUtil.generatePassword(password).equals(apiT_member.getPay_pwd())) {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "支付密码不正确");
			} else {
				if (amount.compareTo(apiT_member.getC_money()) > 0) {// 余额不足
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "余额不足");
				} else {
					// 用户金额变动明细表中插信息
					List<ApiT_order> list = apiT_orderService.findOrderByMap(params);
					if (list == null || list.size() == 0 || list.get(0).getZi_status() == 1) {
						map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
						map.put(Utils.MESSAGE, "订单不存在或已支付");
					} else {
						ApiT_user_cash_records apiT_user_cash_records = new ApiT_user_cash_records();
						apiT_user_cash_records.setUser_id(user_id);
						ApiU_message message = new ApiU_message();
						String nowTimeToString = DateUtil.nowTimeToString();
						for (ApiT_order apiT_order : list) {
							apiT_order.setZi_status(1);// 已支付
							apiT_order.setDd_status(2);// 已付款
							apiT_order.setZf_type("0");
							apiT_order.setPaytime(nowTimeToString);
							apiT_orderService.updateT_order(apiT_order);

							// 广告订单
							if (apiT_order.getOrdertype() == 5) {
								map.put("did", apiT_order.getOrdernum());
								ApiT_order_detail apiT_order_detail = apiT_order_detailMapper
										.findOrderDetailsByMap(map);
								// 广告改为已支付状态
								ApiU_advert advert = advertMapper
										.findU_advertById(Integer.valueOf(apiT_order_detail.getTarget_id()));
								advert.setIs_pay(1);
								advertMapper.updateU_advert(advert);
								// 如果有红包，更新红包的支付状态
								if (advert.getBonus_id() != null && !"".equals(advert.getBonus_id())) {
									ApiU_bonus apiU_bonus = apiU_bonusMapper
											.findU_bonusById(Integer.valueOf(advert.getBonus_id()));
									apiU_bonus.setIs_pay(1);
									apiU_bonusMapper.updateU_bonus(apiU_bonus);
								}
								apiT_user_cash_records.setRemark("购买广告");
								apiT_user_cash_records.setCate_type(5);
								message.setTitle("广告购买成功");
								message.setContent("您购买了广告");
							} else if (apiT_order.getOrdertype() == 6) {
								map.put("did", apiT_order.getOrdernum());
								ApiT_order_detail apiT_order_detail = apiT_order_detailMapper
										.findOrderDetailsByMap(map);
								// 普通红包改为已支付状态
								ApiU_bonus apiU_bonus = apiU_bonusMapper
										.findU_bonusById(Integer.valueOf(apiT_order_detail.getTarget_id()));
								apiU_bonus.setIs_pay(1);
								apiU_bonusMapper.updateU_bonus(apiU_bonus);
								apiT_user_cash_records.setRemark("发红包");
								apiT_user_cash_records.setCate_type(6);
								message.setContent("您发了一个红包");
							} else if (apiT_order.getOrdertype() == 0) {
								String allMoney = apiT_orderMapper.getAllPayMoneyBySerialFlagNo(serialflagno);
								if (Util.getBigDecimal(allMoney).compareTo(amount) == 0) {
									// 购物订单
									apiT_orderMapper.updateDDStatusBySerialFlagNo(serialflagno, "2");// 已付款
									// 扣减库存
									List<ApiT_order_detail> orderDetailList = apiT_order_detailMapper
											.getOrderDetailBySerialFlagNo(serialflagno);
									for (ApiT_order_detail orderDetailObj : orderDetailList) {
										String store = apiT_productsMapper
												.searStoreByProId(orderDetailObj.getProduct_id().toString());
										long num = orderDetailObj.getNum();
										int left = (int) (Integer.parseInt(store) - num);
										apiT_productsMapper.updStoreByProId(orderDetailObj.getProduct_id(), left);
									}
									// 修改购物车
									String cardIds = "";
									List<String> cardIdList = apiT_orderMapper.getCardIdsBySerialFlagNo(serialflagno);
									for (String string : cardIdList) {
										cardIds += string + ",";
									}
									String[] carIdArr = cardIds.split(",");
									for (int i = 0; i < carIdArr.length; i++) {
										apiCarMapper.updateCarByCarId(carIdArr[i], "1");// 已支付
									}
								} else {
									/** start huangshi001 update */
									// 金额校验后期统一处理，其他地方暂不修改
									map.put(Utils.MESSAGE, "支付金额不正确");
									map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
									throw new Exception("支付金额不正确");
									/** end huangshi001 update */
								}
								/** start huangshi001 update */
								apiT_user_cash_records.setRemark("购买了商品");
								apiT_user_cash_records.setCate_type(0);
								message.setTitle("您的宝贝购买成功");
								message.setContent("您在首媒中国-特卖会的订单付款成功，宝贝已整装待发，请耐心等待哦");
							} else if (apiT_order.getOrdertype() == 8) {
								// 暂无逻辑,新发现订单
								// 如果需要修改库存,则需要增加字段
							} else if (apiT_order.getOrdertype() == 9) {
								map.put("did", apiT_order.getOrdernum());
								ApiT_order_detail apiT_order_detail = apiT_order_detailMapper
										.findOrderDetailsByMap(map);
								// 优惠券押金订单,订单为一个，优惠券ID可能为多个
								String target_id = apiT_order_detail.getTarget_id();
								String[] target_id_list = target_id.split(",");
								for (String coupon_id : target_id_list) {
									ApiU_coupon apiU_coupon = apiU_coupon_Mapper
											.findU_couponById(Integer.valueOf(coupon_id));
									apiU_coupon.setDeposit_status(1);
									apiU_coupon_Mapper.updateU_coupon(apiU_coupon);
								}
								apiT_user_cash_records.setCate_type(4);
								apiT_user_cash_records.setRemark("在线交易");
							} else if (apiT_order.getOrdertype() == 10) {
								map.put("did", apiT_order.getOrdernum());
								ApiT_order_detail apiT_order_detail = apiT_order_detailMapper
										.findOrderDetailsByMap(map);
								// 优惠券支付订单
								String target_id = apiT_order_detail.getTarget_id();
								ApiU_coupon_detail apiU_coupon_detail = apiU_coupon_detailMapper
										.findU_coupon_detailById(Integer.valueOf(target_id));
								apiU_coupon_detail.setUse_time(nowTimeToString);
								apiU_coupon_detail.setStatus(1);
								apiU_coupon_detailMapper.U_coupon_detailInsertion(apiU_coupon_detail);
								apiT_user_cash_records.setCate_type(4);
								apiT_user_cash_records.setRemark("在线交易");
							} else if (apiT_order.getOrdertype() == 11) {// 转账
								String touserId = apiT_order.getExt_1();// 转给某用户的
								ApiT_member toMember = apiT_memberMapper.findT_memberById(Integer.valueOf(touserId));
								String createType = apiT_order.getExt_2();// 是否需要对方接受转账
								if ("0".equals(createType)) { // 0-扫码支付（转账），不需要对方确认
									apiT_user_cash_records.setIs_receive(1);// 已领取

									// 已领取则增加一条已领取的记录
									ApiT_user_cash_records receiverecords = new ApiT_user_cash_records();
									receiverecords.setUser_id(touserId);
									receiverecords.setConn_id(apiT_order.getUser_id());
									receiverecords.setCate_type(7);
									receiverecords.setRemark(apiT_order.getC_nick() + " 转账给我");
									receiverecords.setProcess_type(0);
									receiverecords.setIs_receive(1);
									receiverecords.setCreate_time(nowTimeToString);
									receiverecords.setMoney(amount);
									receiverecords.setOrder_id(serialflagno);
									receiverecords.setPay_type(0);
									receiverecords.setPay_type_desc("0");
									apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(receiverecords);
									// 改变结束方的金额
									toMember.setC_money(toMember.getC_money().add(amount));
									apiT_memberMapper.updateT_member(toMember);

									ApiU_message receivemessage = new ApiU_message();
									receivemessage.setContent(apiT_order.getC_nick() + "给您转账了" + amount + "元");
									receivemessage.setTitle("转账");
									receivemessage.setType(10);
									receivemessage.setAdd_time(nowTimeToString);
									receivemessage.setConn_id(list.get(0).getRid());
									receivemessage.setUser_id(toMember.getC_id() + "");
									receivemessage.setIs_read(0);
									apiU_messageMapper.insertU_message(receivemessage);

								} else if ("1".equals(createType)) {// 1-表示普通的转账，需要对方确认，
									apiT_user_cash_records.setIs_receive(0);// 未领取
								}
								apiT_user_cash_records.setConn_id(touserId);
								apiT_user_cash_records.setCate_type(7);
								apiT_user_cash_records.setRemark("转账给 " + toMember.getC_nick());
							}
							/** end huangshi001 update */
						}

						if (list.get(0).getOrdertype() == 11) {// 转账
							message.setContent("您转出了" + amount + "元");
							message.setTitle("转账");
							message.setType(10);
						} else {// 在线交易
							message.setTitle("在线交易");
							message.setType(7);
						}

						apiT_user_cash_records.setCreate_time(nowTimeToString);
						apiT_user_cash_records.setMoney(amount);
						apiT_user_cash_records.setOrder_id(serialflagno);
						apiT_user_cash_records.setPay_type(0);
						apiT_user_cash_records.setPay_type_desc("0");
						apiT_user_cash_records.setProcess_type(1);
						apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(apiT_user_cash_records);
						// 余额支付,更新用户的金额
						apiT_member.setC_money(apiT_member.getC_money().subtract(amount));
						apiT_memberMapper.updateT_member(apiT_member);

						message.setAdd_time(nowTimeToString);
						message.setConn_id(list.get(0).getRid());
						message.setUser_id(user_id);
						message.setIs_read(0);
						apiU_messageMapper.U_messageInsertion(message);

						map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
						map.put(Utils.MESSAGE, "支付成功");
					}
				}
			}
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "用户未设置支付密码");
		}
	}

	@Transactional
	@Override
	public void confirmPaytype(PaytypeConfirmPage paytypeConfirmPage, Map<String, Object> map) throws Exception {
		/**
		 * 1-是否全部余额支付 2-保存
		 */
		/** 用户名 */
		String u_id = paytypeConfirmPage.getU_id();
		/** 使用余额金额 */
		Double useCmoney = paytypeConfirmPage.getUseCmoney();
		/** 总需支付金额 */
		Double sumPrice = paytypeConfirmPage.getSumPrice();
		/** 订单号 */
		String orderIds = paytypeConfirmPage.getOrderIds();
		/** 在线支付方式 ----余额：0 1-支付宝 2-微信 3-货到付款 4-积分兑换 */
		String payType = paytypeConfirmPage.getPayType();
		/** 支付订单号 */
		// String orderIdFlag = paytypeConfirmPage.getOrderIdFlag();

		String[] titleArr = orderIds.split(",");
		List<String> titles = new ArrayList<String>();
		for (String title : titleArr) {
			titles.add(title);
		}

		/** 需要清空之前是否一起支付的标记 订单号：orderIdFlag */
		// List<ApiDingDan> dingDanList1 = apiDingDanMapper
		// .searchDingDanBySerialFlagNo(orderIdFlag);
		// if (dingDanList1 != null && dingDanList1.size() > 0) {
		// for (ApiDingDan dingDan : dingDanList1) {
		// dingDan.setSerialFlagNo("");
		// apiDingDanMapper.updateDingDan(dingDan);
		// }
		// }

		BigDecimal sumPrice1 = new BigDecimal(sumPrice);
		BigDecimal useCmoney1 = new BigDecimal(useCmoney);
		List<ApiDingDan> dingDanList = apiDingDanMapper.searchDingDanByTitles(titles);
		boolean flag = false;// 是否余额支付 false-否 true-是
		Map<String, Object> paramData = new HashMap<String, Object>();
		if (dingDanList != null && dingDanList.size() > 0) {
			// 判断：是充值订单，或充值有礼订单---不允许选择余额支付
			String orderTypeTemp = dingDanList.get(0).getOrderType().toString();
			if (("1".equals(orderTypeTemp) || "2".equals(orderTypeTemp)) && "0".equals(payType)) {// 充值或充值有礼
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "充值订单不能使用余额支付！");
			} else {
				if (useCmoney1.compareTo(sumPrice1) >= 0) {// 余额大于或等于支付金额
					// 全部使用余额支付，直接扣除账户余额，支付成功-------
					BigDecimal sumPayMoney = BigDecimal.ZERO;
					for (ApiDingDan dingdan : dingDanList) {
						dingdan.setZf_type(payType);
						// dingdan.setSerialFlagNo(orderIdFlag);//
						// 支付订单号----判断多个订单是否一起支付
						dingdan.setSerial(dingdan.getTitles());// 余额支付，流水号等于订单号
						dingdan.setZi_status(1);// 已支付
						dingdan.setDd_status(2);// 已付款
						dingdan.setPaytime(new Date());
						dingdan.setRemainmoney(dingdan.getPayMoney());// 全部使用余额支付

						/** 消息推送，每次新产生订单，给商家推送消息 */
						/** 新订单-不是自动接单，且是货到付款或是已付款 */
						// apiTOrderMessageService.sendShopNewOrderMessage(dingdan);
						sumPayMoney = sumPayMoney.add(dingdan.getPayMoney());

						// 生成订单后，商家已接单，添加配送任务---未付款的还没有配送任务
						apiT_shippingService.produceSendTask(dingdan);
					}
					flag = true;
					ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
					// Integer cJf = member.getcJf();
					// if(cJf==null){//订单完成再增加积分
					// cJf = 0;
					// }
					BigDecimal cmoney = member.getCmoney();
					cmoney = cmoney.subtract(sumPayMoney);
					paramData.put("cUserId", u_id);
					paramData.put("cMoney", cmoney);// cUserId
					// paramData.put("cJf", sumPayMoney.intValue()+cJf);
					// 全部余额支付，支付成功，扣除账户余额 //购物--订单--赠送积分--整数---货到付款记得加积分
					apiTmemberMapper.modifyApiTmemberByCuserid(paramData);

					for (ApiDingDan dingdan : dingDanList) {
						apiDingDanMapper.updateDingDanPayInfo(dingdan);
					}
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "success");
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "余额不足");
				}
			}
		}
	}

	@Override
	public ApiDingDan confirmChargeType(Map<String, String> params, Map<String, Object> map) throws Exception {
		String u_id = params.get("u_id");
		String money = params.get("money");
		String payType = params.get("payType");
		Integer city_id = Integer.valueOf(params.get("city_id"));
		ApiDingDan dingDan = new ApiDingDan();
		dingDan.setU_id(u_id);
		dingDan.setMoney(Util.getBigDecimal(money));
		dingDan.setPayMoney(Util.getBigDecimal(money));
		dingDan.setZi_status(0);// 0-已下单未支付
		dingDan.setDd_status(1);// 待付款
		dingDan.setZf_type(payType);
		dingDan.setOrderType(1);// 1-充值订单
		dingDan.setAppdate(new Date());
		ApiT_city city = cityMapper.findT_cityById(city_id);
		String titles = Utils.getDingDanNo(city.getU_name());
		dingDan.setTitles(titles);
		dingDan.setSerialFlagNo(titles);
		dingDan.setEnable(1);// 1-已下单 5-订单完成
		// 单纯充值 没有订单编号
		apiDingDanMapper.saveDingDan(dingDan);
		map.put("datas", dingDan);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
		return dingDan;
	}

	@Override
	public void chargeWriteBack(Map<String, String> params, Map<String, Object> map) throws Exception {
		/**
		 * 根据订单号查询订单 1-修改订单支付状态 2-账户余额加值
		 */
		String out_trade_no = params.get("out_trade_no");
		String trade_no = params.get("trade_no");
		String trade_status = params.get("trade_status");
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(out_trade_no);
		if (dingDan != null && "TRADE_SUCCESS".equals(trade_status)) {
			dingDan.setZi_status(1);// 1-已支付
			dingDan.setDd_status(2);// 已付款
			dingDan.setSerial(trade_no);
			// ---判断充值订单，还是充值有礼的订单
			if (2 == dingDan.getOrderType()) {// 是充值有礼的订单
				apiDingDanMapper.updateDingDanPayInfo(dingDan);
				// enable 不变
				/** 消息推送，每次新产生订单，给商家推送消息 */
				/** 新订单-不是自动接单，且是货到付款或是已付款 */
				apiTOrderMessageService.sendShopNewOrderMessage(dingDan);

				// 生成订单后，商家已接单，添加配送任务---未付款的还没有配送任务
				apiT_shippingService.produceSendTask(dingDan);
			} else {
				dingDan.setEnable(5);// 5-订单已完成
				apiDingDanMapper.updateDingDanPayInfo(dingDan);
			}
			String u_id = dingDan.getU_id();

			// 更新账户余额
			ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
			BigDecimal cMoney = member.getCmoney().add(dingDan.getMoney());
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("cMoney", cMoney);
			param.put("cUserId", u_id);
			apiTmemberMapper.modifyApiTmemberByCuserid(param);
			logger.error("---------充值订单回调--" + out_trade_no + "-" + trade_no + "-" + trade_status + "--------");
			map.put("datas", params);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "success");
		} else {
			map.put("datas", params);
			map.put(Utils.RESULT, Utils.RESULT_RC_NO_DATA);
			map.put(Utils.MESSAGE, "支付回调失败！");
		}

	}

	@Override
	public void payOrderInit(Map<String, String> params, Map<String, Object> map) throws Exception {
		// 根据订单号查询订单信息
		String u_id = params.get("u_id");
		String titles = params.get("titles");
		ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(titles);
		if (dingDan != null && member != null) {
			// 将订单信息返回
			InitPaymentPage initPaymentPage = new InitPaymentPage();
			initPaymentPage.setU_id(u_id);
			initPaymentPage.setOrderIdFlag(dingDan.getTitles());
			initPaymentPage.setOrderIds(dingDan.getTitles());
			initPaymentPage.setCmoney(member.getCmoney());
			initPaymentPage.setSumPrice(dingDan.getPayMoney());
			map.put("datas", initPaymentPage);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "success");
		}
	}

}
